package com.bond.jumper.common;


import com.bond.jumper.common.po.MessageToServer;
import com.bond.jumper.common.util.ImageUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.AttributeKey;

import java.awt.image.BufferedImage;

public class ChannelHolder {

    public static final AttributeKey<String> LICENSE_ATTRIBUTE_KEY = AttributeKey.valueOf("license");

    private static Channel activeChannel;

    private ChannelHolder() {

    }

    public static void holdChannel(Channel channel) {
        activeChannel = channel;
    }

    /**
     * 发送消息
     *
     * @param message
     */
    public static ChannelFuture sendMessage(String message) {
        if (activeChannel != null && activeChannel.isActive()) {
            return activeChannel.writeAndFlush(message);
        }
        return null;
    }

    /**
     * 发送图片
     *
     * @param bufferedImage
     * @return
     */
    public static ChannelFuture sendMessage(BufferedImage bufferedImage) {
        if (activeChannel != null && activeChannel.isActive()) {
            ByteBuf byteBuf = Unpooled.wrappedBuffer(ImageUtils.bufferedImageToByteArray(bufferedImage, ImageUtils.FORMAT_JPEG));
            return activeChannel.writeAndFlush(byteBuf);
        }
        return null;
    }

    /**
     * 发送对象
     * @param messageToServer
     * @return
     */
    public static ChannelFuture sendMessage(MessageToServer messageToServer) {
        if (activeChannel != null && activeChannel.isActive()) {
            return activeChannel.writeAndFlush(messageToServer);
        }
        return null;
    }
}
